<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>简单的模块抖动效果</title>
<!--autor: carriehuang | QQ:453555909 | 转载需注明原处-->
<head>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        body{

        }
        .wrap{
            width:500px;
            height:500px;
            margin: 0 auto;
            position: relative;
        }
        .box{
            width:100px;
            height:100px;
            background-color: #990000;
            position: absolute;
            left: 0px;
            top:40px;
        }
    </style>
</head>
<body>

<div class="wrap">
    <div class="box" id="box"></div>
</div>
<script type="text/javascript">

    window.onload=function(){
        var oBox = document.getElementById("box");
        //点击触发事件
        oBox.onclick = function(){
            shake(oBox,2,"left",function(){
                shake(oBox,2,"top");
            });
        };
        //封装抖动插件
        function shake(obj,spe,dir,endFn){
            var arr = [];
            var num = 0;
            obj.timer = null;
            //循环添加数组的值，即抖动的坐标
            for(var i=20;i>0;i-=spe){
                arr.push(i,-i);
            }
            //最末尾添加0，为了让元素回归原坐标
            arr.push(0);
            //定时器，循环插入元素新坐标，实现抖动效果
            obj.timer = setInterval(function(){
                obj.style[dir] = arr[num]+"px";
                num++;
                if(num==arr.length){
                    //初始化
                    num=0;
                    clearInterval(obj.timer);
                    //判断是否存在函数，不存在则不执行函数，存在则执行函数
                    endFn && endFn();
                }
            },100);
        }

        //判断浏览器，实现获取样式表样式属性的兼容
        function getStyle(obj,attr){
            return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
        }
    }
</script>
</body>

</html>
